package com.sdkx.app.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.sdkx.app.R;
import com.sdkx.app.ViewModel.MarkManager;
import com.sdkx.app.activitys.MainActivity;
import com.sdkx.app.datalayers.LayersFactory;
import com.sdkx.app.datalayers.MarkPointsPanel;
import com.sdkx.app.dialog.markdialog.MarkTypeDialog;
import com.sdkx.app.dialog.markdialog.ModiMarkDialog;
import com.sdkx.app.model.Mark;
import com.sdkx.app.util.Util;
import com.sdkx.app.view.ClearEditText;

import java.util.ArrayList;
import java.util.List;

import static android.media.CamcorderProfile.get;

public class MarkFragment extends BaseFragment implements View.OnClickListener {

    private final static String MARK_TYPE_NAME = "com.sdkx.app.fragment.marktype";
    private final static String MARK_TYPE_KEY = "curmarktype";
    private RecyclerView recyclerView;
    private ClearEditText mClearEdit;
    private ImageView imgSelType;
    private TextView txtSel;
    private ViewGroup viewSelParent;
    private Button mHideAll;
    private int curType = 0;
    List<Mark> marks = new ArrayList<Mark>();
    MarkPointAdapter markPointAdapter;
    Handler handler = new Handler();
    SharedPreferences preferences;//
    boolean visibleflag = true;
    InitTask mInitTask;

    @Nullable
    @Override
    public View onCreateView(@Nullable LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.mark_fragment_layout, container, false);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        view.findViewById(R.id.mark_type).setOnClickListener(this);
        view.findViewById(R.id.delete_all).setOnClickListener(this);
        view.findViewById(R.id.mark_add).setOnClickListener(this);
        view.findViewById(R.id.btn_back).setOnClickListener(this);
        mHideAll = view.findViewById(R.id.hide);
        mHideAll.setOnClickListener(this);
        mClearEdit = view.findViewById(R.id.seach_edit);
        recyclerView = view.findViewById(R.id.recyclerView);
        imgSelType = view.findViewById(R.id.img_sel_type);
        txtSel = view.findViewById(R.id.cur_sel_txt);
        viewSelParent = view.findViewById(R.id.selview_parent);
        viewSelParent.setOnClickListener(this);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(manager);
        markPointAdapter = new MarkPointAdapter();
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(getActivity().getDrawable(R.drawable.listview_divider));
        recyclerView.addItemDecoration(divider);
        recyclerView.setAdapter(markPointAdapter);
        preferences = getActivity().getSharedPreferences(MARK_TYPE_NAME, Context.MODE_PRIVATE);
        curType = preferences.getInt(MARK_TYPE_KEY, 0);

        mClearEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                List<Mark> list = MarkManager.filterData(s.toString(), marks);
                markPointAdapter.setMarklist(list);
            }
        });
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mInitTask = new InitTask();
        mInitTask.execute();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                goBack();
                break;
            case R.id.delete_all: {
                final AlertDialog dlg = new AlertDialog.Builder(getActivity(), AlertDialog.THEME_TRADITIONAL).setMessage("是否删除全部标记点")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                MarkManager.deleteAll();
                                marks.clear();
                                markPointAdapter.setMarklist(marks);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create();
                dlg.show();
            }
            break;
            case R.id.selview_parent:
            case R.id.mark_type:
                final MarkTypeDialog dlg = new MarkTypeDialog(getActivity());
                dlg.setOnSelectListener(new MarkTypeDialog.IMarkTypeListener() {
                    @Override
                    public void onSelect(int position) {
                        curType = position;
                        marks = MarkManager.getItemsByType(curType);
                        MarkManager.sort(marks);
                        markPointAdapter.setMarklist(marks);
                        setSelMarkImg(imgSelType, position);
                        setShapeName(txtSel, position);
                        updateHideButton();
                        dlg.dismiss();
                    }
                });
                dlg.show();
                break;
            case R.id.mark_add:
                ModiMarkDialog adlg = new ModiMarkDialog(getActivity(), null);
                adlg.setiMarkCallback(new ModiMarkDialog.IMarkCallback() {
                    @Override
                    public void onSaveMark(Mark mark) {
                        if (curType < 0 || curType != mark.getType()) {
                            marks = MarkManager.getItemsByType(mark.getType());
                            curType = mark.getType();
                            setSelMarkImg(imgSelType, curType);
                            setShapeName(txtSel, curType);
                            updateHideButton();
                        } else {
                            marks = MarkManager.getItemsByType(mark.getType());
                        }
                        marks = MarkManager.sort(marks);
                        if (markPointAdapter != null)
                            markPointAdapter.setMarklist(marks);
                        updateHideButton();

                    }
                });
                adlg.show();
                break;
            case R.id.hide:
                new MarkVisibleState().execute(!visibleflag);
                break;
        }
    }


    public class MarkPointAdapter extends RecyclerView.Adapter<MarkPointAdapter.MarkHolder> {
        List<Mark> marklist = new ArrayList<Mark>();
        int showcolor = Color.parseColor("#FFFFFF");
        int hidecolor = Color.parseColor("#606060");

        public MarkPointAdapter() {

        }

        public void setMarklist(List<Mark> list) {
            marklist.clear();
            for (Mark mark : list) {
                marklist.add(mark);
            }
            this.notifyDataSetChanged();
        }

        public List<Mark> getMarklist() {
            return marklist;
        }

        @NonNull
        @Override
        public MarkHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new MarkHolder(getLayoutInflater().inflate(R.layout.mark_list_item, null));
        }

        @Override
        public void onBindViewHolder(@NonNull MarkHolder holder, int position) {
            holder.init(position);
        }

        @Override
        public int getItemCount() {
            return marklist.size();
        }

        public class MarkHolder extends RecyclerView.ViewHolder {
            TextView latlon, name, details;
            ImageView markImg;
            Mark mark;
            public MarkHolder(final View itemView) {
                super(itemView);
                itemView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                latlon = itemView.findViewById(R.id.latlon);
                name = itemView.findViewById(R.id.name);
                details = itemView.findViewById(R.id.details);
                markImg = itemView.findViewById(R.id.markimg);
//                itemView.setOnLongClickListener(new View.OnLongClickListener() {
//                    @Override
//                    public boolean onLongClick(final View item) {
//                        final View popview = getLayoutInflater().inflate(R.layout.marklist_menu_layout, null);
//
//                        final PopupWindow popupWindow = new PopupWindow(popview,
//                                200, LinearLayout.LayoutParams.WRAP_CONTENT);
//
//                        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//                        popupWindow.setFocusable(true);
//                        popupWindow.setOutsideTouchable(true);
//                        popupWindow.showAsDropDown(item, item.getWidth() - 20, -(item.getHeight()), Gravity.LEFT | Gravity.TOP);
//                        popview.findViewById(R.id.modify).setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                ModiMarkDialog dialog = new ModiMarkDialog(getActivity(), (Mark) item.getTag());
//                                dialog.setiMarkCallback(new ModiMarkDialog.IMarkCallback() {
//                                    @Override
//                                    public void onSaveMark(Mark mark) {
//                                        if (curType > 0)
//                                            marks = MarkManager.getItemsByType(curType);
//                                        else {
//                                            marks = MarkManager.getItemsByType(curType);
//                                        }
//                                        markPointAdapter.notifyDataSetChanged();
//                                        updateHideButton();
//                                    }
//                                });
//                                dialog.show();
//                                popupWindow.dismiss();
//                            }
//                        });
//                        popview.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                Mark selectMark = (Mark) item.getTag();
//                                markPointAdapter.getMarklist().remove(selectMark);
//                                marks.remove(selectMark);
//                                selectMark.delete();
//                                markPointAdapter.notifyDataSetChanged();
//                                popupWindow.dismiss();
//                            }
//                        });
//                        popview.findViewById(R.id.map).setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                ((MainActivity)getActivity()).getMapControl().slideAnimation(mark.getDoubleLongitude(),mark.getDoubleLatitude());
//                                popupWindow.dismiss();
//                            }
//                        });
//                        return true;
//                    }
//                });
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(final View item) {
                        final View popview = getLayoutInflater().inflate(R.layout.marklist_menu_layout, null);

                        final PopupWindow popupWindow = new PopupWindow(popview,
                                200, LinearLayout.LayoutParams.WRAP_CONTENT);

                        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                        popupWindow.setFocusable(true);
                        popupWindow.setOutsideTouchable(true);
                        popupWindow.showAsDropDown(item, item.getWidth() - 20, -(item.getHeight()), Gravity.LEFT | Gravity.TOP);
                        popview.findViewById(R.id.modify).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ModiMarkDialog dialog = new ModiMarkDialog(getActivity(), (Mark) item.getTag());
                                dialog.setiMarkCallback(new ModiMarkDialog.IMarkCallback() {
                                    @Override
                                    public void onSaveMark(Mark mark) {
                                        if (curType > 0)
                                            marks = MarkManager.getItemsByType(curType);
                                        else {
                                            marks = MarkManager.getItemsByType(curType);
                                        }
                                        markPointAdapter.notifyDataSetChanged();
                                        updateHideButton();
                                    }
                                });
                                dialog.show();
                                popupWindow.dismiss();
                            }
                        });
                        popview.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Mark selectMark = (Mark) item.getTag();
                                markPointAdapter.getMarklist().remove(selectMark);
                                marks.remove(selectMark);
                                selectMark.delete();
                                markPointAdapter.notifyDataSetChanged();
                                popupWindow.dismiss();
                            }
                        });
                        popview.findViewById(R.id.map).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ((MainActivity)getActivity()).getMapControl().slideAnimation(mark.getDoubleLongitude(),mark.getDoubleLatitude());
                                popupWindow.dismiss();
                            }
                        });
                    }
                });
            }

            public void init(int position) {
                 mark = marklist.get(position);
                if (!mark.getIsShow()) {
                    name.setTextColor(hidecolor);
                    latlon.setTextColor(hidecolor);
                    details.setTextColor(hidecolor);
                } else {
                    name.setTextColor(showcolor);
                    latlon.setTextColor(showcolor);
                    details.setTextColor(showcolor);
                }
                name.setText(mark.getName());
                StringBuilder builder = new StringBuilder();
                builder.append(Util.degreePatten(getContext(),mark.getLatitude()));
                builder.append(",");
                builder.append(Util.degreePatten(getContext(),mark.getLongitude()));
                latlon.setText(builder.toString());
                details.setText(mark.getDetails());
                itemView.setTag(mark);
                setSelMarkImg(markImg, mark.getType());
            }
        }
    }

    public void setSelMarkImg(ImageView view, int pos) {
        if (pos < 0) return;
        ArrayList<MarkManager.MarkShape> shapes = MarkManager.getAllMarkShape();
        MarkManager.MarkShape markShape = shapes.get(pos);
        view.setImageResource(markShape.drawableId);
    }

    public void setShapeName(TextView txtview, int id) {
        if (id < 0) return;
        ArrayList<MarkManager.MarkShape> shapes = MarkManager.getAllMarkShape();
        MarkManager.MarkShape markShape = shapes.get(id);
        txtview.setText(markShape.shapName);
    }

    private class InitTask extends AsyncTask<Void, Void, List<Mark>> {

        @Override
        protected List<Mark> doInBackground(Void... voids) {
            marks = MarkManager.getItemsByType(curType);
            marks = MarkManager.filterData("", marks);
            return marks;
        }

        @Override
        protected void onPostExecute(List<Mark> list) {
            MarkManager.MarkShape shape = MarkManager.getAllMarkShape().get(curType);
            imgSelType.setImageResource(shape.drawableId);
            txtSel.setText(shape.shapName);
            markPointAdapter.setMarklist(marks);
            updateHideButton();

        }
    }

    private void updateHideButton() {
        int count = 0;
        for (Mark mark : marks) {
            if (mark.getIsShow()) count++;
        }
        if (count == 0) {
            visibleflag = false;
            mHideAll.setText("全部显示");
        } else {
            mHideAll.setText("全部隐藏");
            visibleflag = true;
        }
    }

    public class MarkVisibleState extends AsyncTask<Boolean, Void, Boolean> {
        ProgressDialog dialog;

        @Override
        protected Boolean doInBackground(Boolean... booleans) {
            boolean flag = booleans[0];
            if (!flag) {
                for (Mark mark : markPointAdapter.getMarklist()) {
                    if (mark.getIsShow()) {
                        mark.setIsShow(false);
                        mark.update(mark.getId());
                    }
                }
            } else {
                for (Mark mark : markPointAdapter.getMarklist()) {
                    if (!mark.getIsShow()) {
                        mark.setIsShow(true);
                        mark.update(mark.getId());
                    }
                }
            }
            return flag;
        }

        @Override
        protected void onPostExecute(Boolean b) {
            dialog.dismiss();
            if (!b.booleanValue()) {
                visibleflag = false;
                mHideAll.setText("全部显示");
            } else {
                visibleflag = true;
                mHideAll.setText("全部隐藏");
            }
            markPointAdapter.notifyDataSetChanged();
            LayersFactory.getInstance().updateSingleCustom(MarkPointsPanel.class, new LayersFactory.IUpdateLister() {
                @Override
                public void onUpdated() {
                    ((MainActivity)getActivity()).getMapControl().refresh();
                }
            });
        }

        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(getActivity(), ProgressDialog.THEME_TRADITIONAL);
            dialog.setTitle("提示");
            dialog.setMessage("正在保存状态");
            dialog.setIndeterminate(false);
            dialog.setCancelable(false);
            dialog.setOnCancelListener(null);
            dialog.show();
        }
    }

    @Override
    public void onDestroyView() {
        mInitTask.cancel(true);
        super.onDestroyView();
    }
}